/**
 * 
 */
package com.flymobi.fw.dbroute;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.log4j.Logger;

/**
 * @author Administrator
 *
 */
public class ClusDataSouce extends BasicDataSource {
	private static Logger log = Logger.getLogger(ClusDataSouce.class);
	List<DataSource> dataSouces=new ArrayList<DataSource>();
	/**
	 * @return the dataSouces
	 */
	public List<DataSource> getDataSouces() {
		return dataSouces;
	}

	/**
	 * @param dataSouces the dataSouces to set
	 */
	public void setDataSouces(List<DataSource> dataSouces) {
		this.dataSouces = dataSouces;
	}

	static int idx=0;

	/* (non-Javadoc)
	 * @see org.apache.commons.dbcp.BasicDataSource#getConnection()
	 */
	@Override
	public Connection getConnection() throws SQLException {
		// TODO Auto-generated method stub
		idx++;
		int size=dataSouces.size();
		if(idx>=size){
			idx=0;
		}
		if(size==0){
			return null;
		}
		log.info("get connection from datasource "+idx);
		return dataSouces.get(idx).getConnection();
	}
	
	@Override
	public Connection getConnection(String username, String password) 
    throws SQLException{
		idx++;
		int size=dataSouces.size();
		if(idx>=size){
			idx=0;
		}
		if(size==0){
			return null;
		}
		return dataSouces.get(idx).getConnection(username,password);
	}
	
}
